<?php
/**
 * Abstract class for calling remote API's
 *
 *
 * @author     Sebastian Skuse <scs@ecs.soton.ac.uk>
 * @copyright  2009-2010 University of Southampton
 * @license    http://<LICENSE-URL>  <LICENSE-NAME>
 * @version    CVS: $1:$
 */
 
abstract class apiCall {
	
	protected $_responseData;
	protected $_responseType;
	protected $_responseURL;
	protected $_source;
	
	protected $_parsedData;

	// Methods that must be implemented by the service class
	abstract public function search();
	abstract public function getResults();
	abstract public static function getName();
	abstract public static function getVisibility();
	abstract public static function getArguments();

	
	final public function makeRequest($url, $dataType){
		$this->_responseType = $dataType;
		// Intercept request. Check the cache first. If it's not here, go grab it from the API.
		
		$cache = new cache($url, 'object', 10); // 10 minute cache timeout
		$cacheStatus = $cache->queryDatabase();
		
		if($cacheStatus['status'] == "EXPIRED"){
			// Data stored in the cache is out of date. Fetch from the remote URL.
			if(ini_get('allow_url_fopen') == 1){
				// file_get_contents is allowed in fopen context.
				// Get data, adhereing to the MAXTIMEOUT constant.
				$result = file_get_contents($url, false, stream_context_create( array( "http" => array("timeout" => SYS_API_MAXTIMEOUT) ) ));
				
				if($result == false){
					// HTTP request failed. Get data from the cache instead.
					$this->_responseData = $cache->get();
					$this->_source = "cache";
				} else {
					// Data is OK. Set to object property and cache.
					$this->_responseData = $result;
					$this->_source = "live";
					// Update the cached copy.
					$cache->set($this->_responseData);
				}
			} else {
				// Check to see if curl is installed.
			}
		} else if($cacheStatus['status'] == "OK") {
			// Data is still valid, serve the local cached copy.
			$this->_responseData = $cacheStatus['data'];
			$this->_source = "cache";
		}

	}

	final public function getRAW(){
		return $this->_responseData;
	}

	final public function getArray(){
		switch(strtolower($this->_responseType)){
		
			case "json":
				return json_decode($this->_responseData, true);
			break;
		
		
		}
	}

	final public function getXML($format = "simplexml"){
		switch( strtolower($this->_responseType) ){
			
			case "simplexml":
				$output = simplexml_load_string($this->_responseData);
			break;
			
			
			// Default to simplexml
			default:
				$output = simplexml_load_string($this->_responseData);
			break;
			
		}
		return $output;
	}
	
	final public function getJSON(){
		return json_encode($this->_responseData);
	}
	
	final public function getSource(){
		return $this->_source;
	}

}

?>